<?php

namespace App\Service\Activity;

use App\Constants\ErrorCode;
use App\Model\CoinLog;
use App\Model\DailyTaskLog;
use App\Model\UserCoin;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;

/**
 * 每日任务领取奖励
 */
class DailyRewardGetService extends BaseService
{
    public function handle()
    {
	//暂时关闭每日任务奖励领取
        return $this->setError(ErrorCode::TASK_REAWRD_FAIL, '任务奖励领取暂未开放');
        $userId = $this->getUserId();
        $taskId = $this->request->input('task_id', 1);
        //任务奖励的金币
        $task = DailyTaskLog::getTask($taskId);
        if (!$task) return $this->setError(ErrorCode::PARAMETER_ERROR, '该任务不存在!');
        $rewardCoin = $task['reward'];

        //发放领取金币
        Db::beginTransaction();
        try {
            $result = DailyTaskLog::getReward($userId, $taskId);
            if (!$result) {
                log_user_result($userId, "Task:{$taskId}==NoTask");
                return $this->setError(ErrorCode::TASK_REAWRD_FAIL, '该任务没有完成,领取奖励失败!');
            }
            //更新账户
            $remainCoin = UserCoin::gainIncome($userId, $rewardCoin);
            //添加流水记录
            CoinLog::addIncome($userId, $rewardCoin, CoinLog::FROM_DAILY_TASK, $remainCoin);
            Db::commit();
        } catch (\Throwable $exception) {
            log_user_result($userId, "Task:{$taskId}==Error:" . $exception->getMessage());
            Db::rollBack();
        }
        $ret['result'] = $result ? 1 : 0;
        return $ret;
    }
}
